#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import cgi
import requests


def error_fun(func):
    def error(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as err:
            print(f"""Content-type:text/html; charset=utf-8

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Error</title>
</head>
<body>
    请求错误！！！{err}
</body>
</html>
""")
        finally:
            return
    return error


def deal_string(string=''):
    string = string.replace(' ', '')  # 去除空格
    if string.__len__() != 4:
        return -1
    return string


def request_imgCode(image):
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic"
    params = {
        "image": image,
    }
    access_token = '请前往百度获取'
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        # print(response.json())
        rec_result = response.json()
        try:
            rec_codeStr = deal_string(rec_result['words_result'][0]['words'])
        except:
            return -1
        if rec_codeStr == -1:
            return -1
        else:
            return rec_codeStr


@error_fun
def main():
    form = cgi.FieldStorage()
    imageBase64 = form.getvalue('imageBase64')
    recv_result = {}  # 设置响应json

    # 二进制方式打开图片文件
    # f = open('1.jpg', 'rb')
    # img = base64.b64encode(f.read())
    # print(img)
    # code = request_imgCode(img)

    code = request_imgCode(imageBase64)

    if code == -1:
        recv_result['status'] = 1
        recv_result['msg'] = "验证码识别失败！正在尝试刷新页面······"
    else:
        recv_result['status'] = 0
        recv_result['msg'] = code

    print(f"""Content-type:text/json; charset=utf-8

{str(recv_result)}
""")


main()
